package com.hmdp.interceptor;

import com.hmdp.dto.UserDTO;

import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 第二重拦截，校验登录状态
 *      查询threadLocal村的用户信息
 *          有则通过
 *          无则return false
 *
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //查询threadLocal存储的用户信息
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null){
            //用户不存在，拦截
            return false;
        }
        //放行
        return true;
    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
